package com.lingxu.base.common.util.encrypt;

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5Utils {

	// 测试
	public static void main(String[] args) {
		System.out.println("md5:" + encrypt("1"));
	}

	/**
	 * 获取特定字符串的MD5码 eg:md5("YEN") 输出：0d9962cb9239354e6da0ca55ebd0b93c
	 * 
	 * @param str
	 * @return
	 */
	public static String encrypt(String str) {
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.update(str.getBytes());
			byte[] b = md.digest();

			int temp;
			StringBuffer sb = new StringBuffer("");
			for (int offset = 0; offset < b.length; offset++) {
				temp = b[offset];
				if (temp < 0)
					temp += 256;
				if (temp < 16)
					sb.append("0");
				sb.append(Integer.toHexString(temp));
			}
			str = sb.toString();

		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return str;
	}
	
	/**
	 * md5加密
	 * @param inputString
	 * @return
	 */
	public static String Md5Encrypt(String inputString){
		byte[] inputData = inputString.getBytes();
		BigInteger md5 = null;
		try {
			md5 = new BigInteger(Coder.encryptMD5(inputData));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return md5.toString(16);
	}
	
	
	/**
	 * SHA加密
	 * 
	 * @param inputString
	 * @return
	 * @throws Exception
	 */
	public static String shaEncrypt(String inputString) throws Exception {
		byte[] inputData = inputString.getBytes();
		BigInteger sha = new BigInteger(Coder.encryptSHA(inputData));
		return sha.toString(32);
	}
	
	/**
	 * HMAC加密
	 * 
	 * @param inputString
	 * @return
	 * @throws Exception
	 */
	public static String macEncrypt(String inputString) throws Exception {
		byte[] inputData = inputString.getBytes();
		BigInteger mac = new BigInteger(Coder.encryptHMAC(inputData,
				inputString));
		return mac.toString(16);
	}
}
